package org.codehaus.activemq.spring;

import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;

public class ActiveMQDtdResolver
  implements EntityResolver
{
  private static final String DTD_NAME = "activemq.dtd";
  private static final String SEARCH_PACKAGE = "/org/codehaus/activemq/";
  protected final Log logger = LogFactory.getLog(getClass());

  public InputSource resolveEntity(String publicId, String systemId) throws IOException {
    this.logger.debug("Trying to resolve XML entity with public ID [" + publicId + "] and system ID [" + systemId + "]");

    if ((systemId != null) && (systemId.indexOf("activemq.dtd") > systemId.lastIndexOf("/")))
    {
      String dtdFile = systemId.substring(systemId.indexOf("activemq.dtd"));
      this.logger.debug("Trying to locate [" + dtdFile + "] under [" + "/org/codehaus/activemq/" + "]");
      try {
        String name = "/org/codehaus/activemq/" + dtdFile;
        Resource resource = new ClassPathResource(name, getClass());
        InputSource source = new InputSource(resource.getInputStream());
        source.setPublicId(publicId);
        source.setSystemId(systemId);
        this.logger.debug("Found beans DTD [" + systemId + "] in classpath");
        return source;
      }
      catch (IOException ex) {
        this.logger.debug("Could not resolve beans DTD [" + systemId + "]: not found in classpath", ex);
      }
    }

    return null;
  }
}